! function () {
    // if (window != top) {
    // 	if (typeof window.parent.api == 'object') {
    // 		window.api = window.parent.api;
    // 		setTimeout(initApiready, 0.8 * 1000);
    // 	}
    // }
    initApiready();
}();

// apiready = initApiready;

function initApiready() {

    ajaxConfig();

    historybackup();

    // keepScreen.off();

    // fixedHeight();

	/*if(typeof isUpdate == 'undefined') {
	    // 加载更新模块
	    includeModal('css', api.wgtRootDir + '/plug/update/update.css');
	    includeModal('js', api.wgtRootDir + '/plug/update/update.js');
	}*/

    // checkRunFrame();

    if (typeof apireadyMap == 'object' && apireadyMap instanceof Array) {
        apireadyMap.forEach(function (value, index, array) {
            typeof value == 'function' ? value() : void (0);
        });
    }
};

// ----------------------------------------------------------------------

// 判断有无iframe
function checkRunFrame() {
    var nodes = document.getElementsByTagName('iframe');
    if (nodes.length <= 0) return;
    for (var i = 0; i < nodes.length; i++) {
        var frame = nodes[i];
        if (typeof api == 'object') frame.contentWindow['api'] = api;
        frame.contentWindow.apiready();
        //setTimeout(frame.contentWindow.initApiready, 1000);
    }
}

// ----------------------------------------------------------------------

/**
 * 加载子页面
 * @param {Object} dom as 容器
 * @param {Object} frameClassName as 每个iframe的统一样式名
 */
function LoadSubPage(opts) {
    var dom = opts.dom || null;
    var frameClassName = opts.frameClassName || '';
    this.group = Number(Math.random().toString().substr(3) + Date.now()).toString(36);
    this.container = dom;
    this.frameClassName = frameClassName;
    var allframe = [];
    this.allframe = allframe;
    this.otherHide = function () {
        for (var i in allframe) {
            allframe[i].style.display = 'none';
        }
    }
}

/**
 * 打开子页面
 * @param {string} name as getElementById
 * @param {string} src
 * @param {function} callback
 */
LoadSubPage.prototype.open = function (name, src, callback) {
    var self = this;
    if (!name || !src) return;
    // 隐藏其余的
    self.otherHide();
    var id = 'iframe-' + name;
    var frame = document.getElementById(id);
    if (frame) {
        frame.style.display = 'block';
        callback && callback();
    } else {
        var frame = document.createElement('iframe');
        frame.id = id;
        frame.name = 'iframe-' + self.group;
        frame.className = self.frameClassName;
        frame.src = src;
        frame.onload = callback || new Function;
        self.container.appendChild(frame);
        self.allframe.push(frame);
    }
};

LoadSubPage.prototype.refresh = function (name, callback) {

}

// ----------------------------------------------------------------------

// 固定高度
function fixedHeight() {
	/*var wrap = D('.wrap');
	if(!wrap) return;*/
    // 高度
    var h = document.documentElement.clientHeight;
    //wrap.style.height = h + 'px';
    document.body.style.height = h + 'px';
}

// ----------------------------------------------------------------------

// 清除缓存
function clearCache(fn) {
    if (!window.api) return;
    api.clearCache(function () {
        //api.toast({
        //  msg : '清除完成'
        //});
        typeof fn == 'function' ? fn() : repage('sign.login.html');
    });
}

// ----------------------------------------------------------------------

// open new frame
function openNewFrame(name, url) {
    if (typeof api != 'undefined') {
        api.execScript({
            name: 'root',
            script: 'createNewFrame("' + name + '", "' + url + '");'
        });
    }
}

// ----------------------------------------------------------------------

// 后退或退出
function historybackup() {
    var domGoback = D('.action-goback');
    if (domGoback) {
        domGoback.onclick = function () {
            // goback
            window.history.back();
        }
    }
    var domClose = D('.action-close');
    if (domClose) {
        domClose.onclick = function () {
            var name = this.getAttribute('data-frame');
            if (typeof api != 'undefined') {
                api.execScript({
                    name: 'root',
                    script: 'closeAFrame("' + name + '")'
                });
            }
        }
    }
}

// jude goback or exit or cancelAjax
function keybackCallback() {
    var domGoback = document.querySelector('.action-goback');
    if (domGoback) {
        domGoback.click();
        return;
    }
    var domClose = document.querySelector('.action-close');
    if (domClose) {
        domClose.click();
        return;
    }
    api.closeWidget();
}

// ----------------------------------------------------------------------

// 跳转页面
function repage(url) {
    window.location.replace(url);
}

// ----------------------------------------------------------------------

// 绑定监听事件
function addEventHandler(target, type, fn) {
    if (target.addEventListener) {
        target.addEventListener(type, fn);
    } else {
        target.attachEvent("on" + type, fn);
    }
}

//移除监听事件
function removeEventHandler(target, type, fn) {
    if (target.removeEventListener) {
        target.removeEventListener(type, fn);
    } else {
        target.detachEvent("on" + type, fn);
    }
}

//复制
function copy(e) {
    var val = e.getAttribute("data-val");
    var oInput = document.createElement('input');
    oInput.value = val;
    document.body.appendChild(oInput);
    oInput.select(); // 选择对象
    oInput.setSelectionRange(0, oInput.value.length);
    var copy_res = document.execCommand("copy"); // 执行浏览器复制命令
    document.body.removeChild(oInput);
    if (copy_res) {
        modal.tips("复制成功");
    } else {
        modal.tips("复制失败，请重试");
    }
}

// 获取元素
function D(selector) {
    return document.querySelector(selector);
}

// 获取元素
function DS(selector) {
    return document.querySelectorAll(selector);
}

// ----------------------------------------------------------------------

// app切换到前台
var listenerResumeCallback = {
    queue: [],
    init: function () {
        var self = listenerResumeCallback;
        for (var i in self.queue) {
            if (typeof self.queue[i] == 'function') {
                self.queue[i]();
            }
        }
    }
};

// 切换后台
var listenerPauseCallback = {
    queue: [],
    init: function () {
        var self = listenerPauseCallback;
        for (var i in self.queue) {
            if (typeof self.queue[i] == 'function') {
                self.queue[i]();
            }
        }
    }
};

// ----------------------------------------------------------------------

// 阻止页面休眠
var keepScreen = {
    on: function () {
        if (typeof api != 'undefined') {
            api.setKeepScreenOn({
                keepOn: true
            });
        }
    },
    off: function () {
        if (typeof api != 'undefined') {
            api.setKeepScreenOn({
                keepOn: false
            });
        }
    }
};

// ----------------------------------------------------------------------

//配置ajax状态码
function ajaxConfig() {
    var host = tool.storage.get('APP_HOST') || '';
    // var host = 'https://qiyun.kojo.club';
    ajax.config.host(host);
    ajax.config.state({
        200: true,
        201: true,
        204: true
    });
    ajax.config.status({
        403: function (res) {
            modal.tips(res.error, function () {
                window.location.href = 'sign.login.html';
            });
            return false;
        },
        500: function (res) {
            //$("body").html(res.data);
			/*console.dir(500);
			console.dir(JSON.stringify(res))*/
            return false;
        }
    });
    ajax.root = function (data_opt) {
        if (!data_opt) return;
        if (typeof data_opt.header == 'undefined') {
            data_opt['header'] = {};
        }
        data_opt.header['jwt-token'] = tool.storage.get('JWT-TOKEN');
        ajax.xhr(data_opt);
    }
}

// ----------------------------------------------------------------------

// 加载模块
function includeModal(type, path, callback) {
    var head = document.getElementsByTagName('head')[0];

    if (type === 'css') {
        var node = document.createElement("link");
        node.type = "text/css";
        node.rel = "stylesheet";
        node.href = path + '#' + new Date().getTime();
        if (callback) {
            node.onload = callback;
        }
        head.appendChild(node);
    }

    if (type === 'js') {
        var node = document.createElement('script');
        node.type = 'text/javascript';
        node.src = path + '#' + new Date().getTime();
        if (callback) {
            node.onload = callback;
        }
        head.appendChild(node);
    }
}

// ----------------------------------------------------------------------

// 队列
function Queue(callback) {
    this.arr = [];
    this.callback = callback || new Function('');
}

// 队列 -- 添加
Queue.prototype.add = function (fn) {
    var self = this;
    self.arr.push(fn);
}

// 队列 -- 运行
Queue.prototype.run = function () {
    var self = this;
    if (self.arr.length <= 0) {
        self.callback();
        return;
    }
    var fn = self.arr[0];
    fn(function () {
        // 删除第一个数组
        self.arr.splice(0, 1);
        // 递归执行
        self.run();
    });
}

// 队列 -- 中止
Queue.prototype.abort = function () {
    var self = this;
    self.arr = [];
    self.callback();
}

// ----------------------------------------------------------------------

/**
 * 初始化tab切换按钮
 * @param {Number} idx as 默认选择第几个
 * @return {Function} getActiveItem
 */
function initLayoutTab(opts) {
    if (typeof opts.tabhead == 'undefined') return;
    var activeIndex = opts.index || 0;
    var mounted = typeof opts.mounted == 'function' ? opts.mounted : new Function('');
    var callback = typeof opts.callback == 'function' ? opts.callback : new Function('');
    var layoutTabItems = [];

    var nodes = opts.tabhead.getElementsByTagName('a');

    for (var i = 0; i < nodes.length; i++) {
        var layoutTabItem = nodes[i];
        if (layoutTabItem.classList.contains('layout-tab-item')) {
            // 记录
            layoutTabItems.push(layoutTabItem);
            // 默认选择第一个
            if (i == activeIndex) {
                activeIndex = i;
                layoutTabItem.classList.add('active');
                setTimeout(function () {
                    mounted.call(null);
                }, 100);
            }
            bind(layoutTabItem, i);
        }
    }
    nodes = null;

    function bind(layoutTabItem, index) {
        // 绑定tab切换按钮
        layoutTabItem.onclick = function () {
            var obj = this;
            layoutTabItems[activeIndex].classList.remove('active');
            obj.classList.add('active');
            activeIndex = index;
            callback.call(null);
        }
    }

    return function () {
        return layoutTabItems[activeIndex];
    }
}

// ----------------------------------------------------------------------

// 新版选项卡
function LayoutTab(opts) {
    if (!opts.tabHeadID) return;
    if (!opts.tabItemCN) return;

    // 静态属性
    this.isLock = false;
    this.target = null;
    this.activeIndex = typeof opts.index == 'number' ? opts.index : '';
    this.callback = typeof opts.callback == 'function' ? opts.callback : new Function('');
    // 选项卡集合
    this.tabItems = [];
    this.tabHeadID = opts.tabHeadID;
    this.tabItemCN = opts.tabItemCN;

    // 初始化
    LayoutTabInit.call(this);
}

// 更新
LayoutTab.prototype.update = function () {
    var self = this;
    // 初始化
    LayoutTabInit.call(self);
}

// 重置
LayoutTab.prototype.resset = function () {
    var self = this;
    // 重置
    self.tabItems[self.activeIndex] && self.tabItems[self.activeIndex].classList.remove('active');
    self.isLock = false;
    self.target = null;
    self.activeIndex = '';
    // 初始化
    LayoutTabInit.call(self);
}

// [锁定|解锁]
LayoutTab.prototype.lock = function (judge) {
    var self = this;
    self.isLock = judge;
}

function LayoutTabInit() {
    var self = this;

    // 清空
    self.tabItems = [];

    // ----------------------------------------------------------------

    // 获取容器
    var tabHeadDom = document.getElementById(self.tabHeadID);

    // 获取选项卡集合
    var nodes = tabHeadDom.getElementsByTagName('*');
    var idx = 0;
    for (var i = 0; i < nodes.length; i++) {
        var layoutTabItem = nodes[i];
        if (layoutTabItem.classList.contains(self.tabItemCN)) {
            // 记录
            self.tabItems.push(layoutTabItem);
            // 绑定事件
            LayoutTabBind.call(self, layoutTabItem, idx);
            // 默认选择第一个
            LayoutTabIsEqual.call(self, idx, layoutTabItem);
            ++idx;
        }
    }
    nodes = null;
}

function LayoutTabBind(layoutTabItem, index) {
    var self = this;
    // --------------------------------------
    // 绑定tab切换按钮
    layoutTabItem.onclick = function () {
        // 判断是否锁定
        if (self.isLock) return;
        self.tabItems[self.activeIndex] && self.tabItems[self.activeIndex].classList.remove('active');
        layoutTabItem.classList.add('active');
        // -----------------------------------
        self.activeIndex = index;
        self.target = self.tabItems[self.activeIndex];
        self.callback.call(self);
    }
}

function LayoutTabIsEqual(idx, layoutTabItem) {
    var self = this;
    // -----------------------------------------
    if (idx === self.activeIndex) {
        setTimeout(function () {
            layoutTabItem.click();
        }, 100);
    }
}

// ----------------------------------------------------------------------

// 单次执行
function Once() {
    this.opts = {};
}

// 检查
Once.prototype.check = function (name) {
    var self = this;
    return self.opts[name];
}

// 锁定
Once.prototype.lock = function (name) {
    var self = this;
    var judge = null;
    if (typeof self.opts[name] == 'boolean') {
        if (self.opts[name] === true) {
            judge = true;
        } else {
            judge = false;
        }
    } else {
        judge = false;
    }
    self.opts[name] = true;
    return judge;
}

// 解锁
Once.prototype.unlock = function (name) {
    var self = this;
    self.opts[name] = false;
}

// ----------------------------------------------------------------------

// 语音播放
function AudioBF() {
    this.audios = {};
}

// name: [cutdown|scene|opend]
AudioBF.prototype.init = function (name) {
    var self = this;
    var dom = document.createElement('audio');
    dom.src = '../music/music/' + name + '.mp3';
    document.body.appendChild(dom);
    self.audios[name] = dom;
}

// 播放
AudioBF.prototype.play = function (name) {
    var self = this;
    var dom = self.audios[name];
    if (dom) dom.play();
}

// 暂停
AudioBF.prototype.pause = function (name) {
    var self = this;
    var dom = self.audios[name];
    if (dom) {
        dom.pause();
        dom.currentTime = 0;
    }
}

// 设置
AudioBF.prototype.config = function (name, opts) {
    var self = this;
    for (var i in opts) {
        self.audios[name][i] = opts[i];
    }
}

// 是否静音
AudioBF.prototype.muted = function (name, judge) {
    var self = this;
    var dom = self.audios[name];
    if (dom) dom.muted = judge;
}

// 是否静音所有
AudioBF.prototype.mutedAll = function (judge) {
    var self = this;
    for (var i in self.audios) {
        self.audios[i].muted = judge;
    }
}
